package org.dromara.bclt.service.impl;

import org.dromara.bclt.domain.DeviceInfo;
import org.dromara.bclt.domain.vo.DeviceInfoVo;
import org.dromara.bclt.mapper.DeviceInfoMapper;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.dromara.bclt.domain.bo.PusheBo;
import org.dromara.bclt.domain.vo.PusheVo;
import org.dromara.bclt.domain.Pushe;
import org.dromara.bclt.mapper.PusheMapper;
import org.dromara.bclt.service.IPusheService;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Collection;
import java.util.stream.Collectors;

/**
 * 手环-消息推送Service业务层处理
 *
 * @author YHGao
 * @date 2024-10-21
 */
@RequiredArgsConstructor
@Service
public class PusheServiceImpl implements IPusheService {

    private final PusheMapper baseMapper;

    private final DeviceInfoMapper deviceInfoMapper;

    /**
     * 查询手环-消息推送
     *
     * @param id 主键
     * @return 手环-消息推送
     */
    @Override
    public PusheVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询手环-消息推送列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 手环-消息推送分页列表
     */
    @Override
    public TableDataInfo<PusheVo> queryPageList(PusheBo bo, PageQuery pageQuery) {
        //根据deviceNumber查询deviceId
        if(bo.getDeviceNumber() != null) {
            DeviceInfoVo deviceInfoVo = deviceInfoMapper.selectVoOne(new LambdaQueryWrapper<DeviceInfo>()
                .select(DeviceInfo::getId)
                .eq(DeviceInfo::getDeviceNumber, bo.getDeviceNumber()));
            Long deviceId = null;
            if(deviceInfoVo != null) {
                deviceId = deviceInfoVo.getId();
            }
            bo.setDeviceId(deviceId);
        }

        // 当client=1时，使用自定义查询逻辑
        if (bo.getClient()!= null && bo.getClient() == 1 && bo.getCreateTime() != null) {
            LocalDate queryDate  = bo.getCreateTime().toInstant()
                    .atZone(ZoneId.systemDefault())
                    .toLocalDate();
            LocalDateTime startTime = queryDate.atStartOfDay();
            LocalDateTime endTime = queryDate.atTime(LocalTime.MAX);

            System.out.println("查询日期: " + queryDate + ", startTime: " + startTime);

            // 构建自定义查询条件，避免createTime精确匹配
            LambdaQueryWrapper<Pushe> lqw = Wrappers.lambdaQuery();
            lqw.eq(bo.getId() != null, Pushe::getId, bo.getId());
            lqw.eq(bo.getDeviceId() != null, Pushe::getDeviceId, bo.getDeviceId());
            lqw.eq(StringUtils.isNotBlank(bo.getPusheType()), Pushe::getPusheType, bo.getPusheType());
            lqw.eq(StringUtils.isNotBlank(bo.getTitle()), Pushe::getTitle, bo.getTitle());
            lqw.eq(StringUtils.isNotBlank(bo.getContent()), Pushe::getContent, bo.getContent());
            lqw.eq(bo.getPusheTime() != null, Pushe::getPusheTime, bo.getPusheTime());
            lqw.eq(StringUtils.isNotBlank(bo.getMessageStatus()), Pushe::getMessageStatus, bo.getMessageStatus());
            // 使用日期范围查询替代精确匹配
            lqw.between(Pushe::getCreateTime, startTime, endTime);

            Page<PusheVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
            return TableDataInfo.build(result);
        } else {
            // 其他情况使用原有的查询逻辑
            LambdaQueryWrapper<Pushe> lqw = buildQueryWrapper(bo);
            Page<PusheVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
            return TableDataInfo.build(result);
        }
    }

    /**
     * 查询符合条件的手环-消息推送列表
     *
     * @param bo 查询条件
     * @return 手环-消息推送列表
     */
    @Override
    public List<PusheVo> queryList(PusheBo bo) {
        LambdaQueryWrapper<Pushe> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<Pushe> buildQueryWrapper(PusheBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<Pushe> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getId() != null, Pushe::getId, bo.getId());
        lqw.eq(bo.getDeviceId() != null, Pushe::getDeviceId, bo.getDeviceId());
        lqw.eq(StringUtils.isNotBlank(bo.getPusheType()), Pushe::getPusheType, bo.getPusheType());
        lqw.eq(StringUtils.isNotBlank(bo.getTitle()), Pushe::getTitle, bo.getTitle());
        lqw.eq(StringUtils.isNotBlank(bo.getContent()), Pushe::getContent, bo.getContent());
        lqw.eq(bo.getPusheTime() != null, Pushe::getPusheTime, bo.getPusheTime());
        lqw.eq(StringUtils.isNotBlank(bo.getMessageStatus()), Pushe::getMessageStatus, bo.getMessageStatus());
        lqw.eq(bo.getCreateTime() != null, Pushe::getCreateTime, bo.getCreateTime());
        return lqw;
    }

    /**
     * 新增手环-消息推送
     *
     * @param bo 手环-消息推送
     * @return 是否新增成功
     */
    @Override
//    public Boolean insertByBo(PusheBo bo) {
//        Pushe add = MapstructUtils.convert(bo, Pushe.class);
//        validEntityBeforeSave(add);
//        boolean flag = baseMapper.insert(add) > 0;
//        if (flag) {
//            bo.setId(add.getId());
//        }
//        return flag;
//    }
    @Transactional(rollbackFor = Exception.class)
    public Boolean insertByBo(PusheBo bo) {

        int sum = 0;//用于跟踪插入成功得个数。
        // 遍历设备 ID 列表
        for (Long deviceId : bo.getDeviceIdList()) {
            // 创建一个新的 Pushe 实体对象，并设置相关属性
            Pushe add = new Pushe();
            add.setDeviceId(deviceId); // 设置设备 ID
            add.setPusheType(bo.getPusheType()); // 设置消息推送类型
            add.setTitle(bo.getTitle()); // 设置标题
            add.setContent(bo.getContent()); // 设置内容
            add.setPusheTime(bo.getPusheTime()); // 设置推送时间
            add.setMessageStatus(bo.getMessageStatus()); // 设置消息状态
//            add.setCreateBy(bo.getCreateBy()); // 设置创建人
//            add.setCreateTime(bo.getCreateTime()); // 设置创建时间

            validEntityBeforeSave(add);

            // 插入数据库，并检查插入是否成功
            boolean flag = baseMapper.insert(add) > 0 ;
            if (flag) {
                sum ++;
            }

            if (flag) {
                bo.setId(add.getId());
            }
        }
        return sum == bo.getDeviceIdList().size();// 返回所有插入操作的结果
    }

    @Override
    public Boolean insertMessageByBo(PusheBo bo) {
        System.out.println("bo = " + bo.toString());
        if(bo.getDeviceNumber() != null) {

            DeviceInfoVo deviceInfoVo = deviceInfoMapper.selectVoOne(new LambdaQueryWrapper<DeviceInfo>()
                .select(DeviceInfo::getId)
                .eq(DeviceInfo::getDeviceNumber, bo.getDeviceNumber()));
            Long deviceId = null;
            if(deviceInfoVo != null) {
                deviceId = deviceInfoVo.getId();
            }
            bo.setDeviceId(deviceId);
        }
        // 创建一个新的 Pushe 实体对象，并设置相关属性
        Pushe add = new Pushe();
        add.setDeviceId(bo.getDeviceId()); // 设置设备 ID
        add.setTitle(bo.getTitle()); // 设置标题
        add.setContent(bo.getContent()); // 设置内容
        add.setPusheTime(bo.getPusheTime()); // 设置推送时间
        System.out.println("bo.getPusheTime():" + bo.getPusheTime());

        add.setMessageStatus(bo.getMessageStatus()); // 设置消息状态
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }


    /**
     * 修改手环-消息推送
     *
     * @param bo 手环-消息推送
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(PusheBo bo) {

        Pushe update = MapstructUtils.convert(bo, Pushe.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(Pushe entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除手环-消息推送信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }
}
